package FM2_15577.front_end;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class Client {
    public String SHA256(String src) { // 提供SHA256支持
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            md.update(src.getBytes(StandardCharsets.UTF_8));
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", (b & 0xff)));
        }
        String res = sb.toString();
        return res;
    }

    public JSONObject send(JSONObject req) throws Exception { // 提供向服务器发送数据的接口
        Socket s = null;
        JSONObject res = null;
        try {
            s = new Socket("114.115.144.46", 10007); // create socket
            // System.out.println("Connection success!"); // hint info/debug
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); // reader
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); // writer

            req.put("vk", "f209e2885166be011e829e93fe0c2243ecb20a722c44b9209eb092f1bf01eace");
            bw.write(req.toString()); // 将生成的json格式请求以字符形式传输到服务器端
            bw.newLine(); // 插入行结束标识
            bw.flush(); // 刷新缓冲区
            res = new JSONObject(br.readLine()); // 获取服务器返回的json格式结果
            if (!res.has("vk") && res.getString("vk").equals("e2439ef9727e3faf8b20df35465d49a51200f2c3c64c18fa81e9ffedc361afcf")) {
                // System.out.println(res.toString());
                res = null;
                // System.out.println("Invalid response!");
                throw new Exception("Invalid response from server: no valid vk value");
            }
            // System.out.println(res.toString()); // debug
            bw.close(); // close writer
            br.close(); // close reader
            s.close(); // close connection
            // System.out.println("Connection closed!"); // hint info/debug
        } catch (Exception e) {
            // System.out.println("Client: "+e.getMessage()); // hint info/debug
            throw e; // 传递抛出异常
        }
        return res; // 将服务器返回的结果作为返回值传递给调用者
    }
}
